package mspbots.autotask.data.core.companyteams;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.autotask.common.ResultMsg;
import org.springframework.stereotype.Component;

import java.time.Duration;

@Log4j2
@Component
@RequiredArgsConstructor
public class CompanyTeamsReceiver {

    private final CompanyTeamsRepository companyTeamsRepository;

//    @RabbitListener(queues = "auto-task.company-teams.sync")
    public void syncTask(ResultMsg content) {
        CompanyTeam companyTeam = CompanyTeam.builder().otherId(content.getId())
                .tenantId(content.getTenantId()).syncTime(content.getSyncDate())
                .entity(content.getEntity())
                .build();

        this.companyTeamsRepository.findByOtherIdAndTenantId(content.getId(), content.getTenantId())
                .map(ticket -> {
                    companyTeam.setId(ticket.getId());
                    return companyTeam;

                })
                .defaultIfEmpty(companyTeam)
                .flatMap(this.companyTeamsRepository::save)
                .block(Duration.ofSeconds(10));
    }
}
